package org.sql.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.sql.spring.PropertyPlaceholderConfigurerExt;
import org.tools.string.StringUtil;

/** 
 * 应用工具，获取properties配置信息
 *
 * <pre> 
 * 构建组：e-jdbc
 * 作者：eddy
 * 邮箱：1546077710@qq.com
 * 日期：2017年4月25日-下午10:14:58
 * 版权：E源时代
 * </pre>
 */
public class AppUtil implements ApplicationContextAware{
	
	protected static final Logger logger = LoggerFactory.getLogger(AppUtil.class);
	private static ApplicationContext context;

	public void setApplicationContext(ApplicationContext _context)
			throws BeansException {
		context = _context;
	}
	
	/**
	 * 获取spring容器上下文。
	 * 
	 * @return ApplicationContext
	 */
	public static ApplicationContext getApplicaitonContext() {
		return context;
	}
	
	/**
	 * 根据beanId获取配置在系统中的对象实例。
	 * 
	 * @param beanId
	 * @return Object
	 * @exception
	 * @since 1.0.0
	 */
	public static Object getBean(String beanId) {
		try {
			return context.getBean(beanId);
		} catch (Exception ex) {
			logger.error("getBean:" + beanId + "," + ex.getMessage(),ex);
		}
		return null;
	}

	/**
	 * 获取Spring容器的Bean
	 * 
	 * @param beanClass
	 * @return T
	 * @since 1.0.0
	 */
	public static <T> T getBean(Class<T> beanClass) {
		try {
			return context.getBean(beanClass);
		} catch (Exception ex) {
			logger.error("getBean:" + beanClass + "," + ex.getMessage(),ex);
		}
		return null;
	}

	/**
	 * 获取系统属性。
	 * 
	 * @param property
	 *            属性键值
	 * @param defaultValue
	 *            默认值
	 * @return String
	 */
	public static String getProperty(String property, String defaultValue) {
		PropertyPlaceholderConfigurerExt config = (PropertyPlaceholderConfigurerExt) getBean("propPlaceHolder");
		String v = config.getValue(property);
		return StringUtil.isEmpty(v)?defaultValue:v.trim();
	}

	/**
	 * 获取系统属性值。
	 * 
	 * @param property
	 *            属性键值。
	 * @return String
	 */
	public static String getProperty(String property) {
		return getProperty(property, "");
	}

}
